//
//  WBNetworkTools.swift
//  微博
//
//  Created by lipengfei on 15/9/4.
//  Copyright © 2015年 lipengfei. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa

enum RequestMethod:String{
    case GET = "GET"
    case POST = "POST"
}
class WBNetworkTools: AFHTTPSessionManager {

///  单例 
    static let sharedTools:WBNetworkTools = {
     var instance = WBNetworkTools(baseURL: nil)
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
///  定义app 信息
    private var clientId = "2110118750"
    private let appSecret = "f5b82697d05193f04274bf714a87bc57"
    let redirectUri = "http://www.baidu.com"
     ///OAuth 授权URL
    /// -see:[http://open.weibo.com/wiki/Oauth2/authorize]](http://open.weibo.com/wiki/Oauth2/authorize])
    var oAuthUrl:NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    // MARK: - 微博数据
    ///获取微博数据
    //加载微博数据，只要一个token值作为get参数
    ///  - returns: 含有微博数据的信号
    /// - see: [https://api.weibo.com/2/statuses/home_timeline.json](https://api.weibo.com/2/statuses/home_timeline.json)
    func loadStatus() ->RACSignal{
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        return request(.GET, urlString: urlString, parameters: nil)
    }
///  封装AFN网络访问
    func request(method:RequestMethod,urlString:String,var parameters:[String:AnyObject]?,withToken:Bool = true) ->RACSignal{
        
            return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
                // 判断是否需要token，默认都是需要的
                // 当 第一次请求网络，获取token的时候，token是不存在的，所以如果依然使用默认的话，会直接进入if语句，然后返回nil，
                // 
                if withToken{
                    //由于没有传递token值进来，需要token，所以首先获取token 值
                    //从用户模型中获取token
                    // guard是与if let相反的，即 如果值为空执行
                   //if let 是：如果有值，执行代码
                    // guard let   else  如果没有值，执行代码
                    guard let token = WBUserAccountViewModel.sharedUserAccount.accessToke else{
                        subscriber.sendError(NSError(domain: "lipengfei", code: -1001
                            , userInfo: ["errorMessage" : "Token为空"]))
                        return nil
                    }
                    // 获取到token之后，判断是否传递了参数，如果没有传递parameters ，需要初始化parameters
                    if parameters == nil{
                        parameters = [String: AnyObject]()
                    }
                    //初始化parameters 之后，后续的token都是有值的
                    parameters!["access_token"] = token
                    
                }
                //成功的回调闭包
                let successCallBack = {(task:NSURLSessionDataTask, result:AnyObject) -> Void in
                    // 将结构返回给 订阅者
                    subscriber.sendNext(result)
                    //完成
                    subscriber.sendCompleted()
                }
                let failureCallBack = {(task:NSURLSessionDataTask, error:NSError) -> Void in
                    print(error)
                    subscriber.sendError(error)
                }
                if method == .GET{
                    self.GET(urlString, parameters: parameters, success: successCallBack, failure: failureCallBack)
                }
                else
                {
                    self.POST(urlString, parameters: parameters, success: successCallBack, failure: failureCallBack)
                }
                return nil
            })
        }
///  获取AccessToken
    
    func loadAccessToken(code:String) ->RACSignal{
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        return request(.POST, urlString: urlString, parameters: params,withToken: false)
    }
    ///  通过用户id 和token，获取用户的信息，发送get请求
    ///- see:[http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    
    
    ///  加载用户信息
    ///
    ///  - parameter uid:          uid
    ///  - parameter access_token:  access_token
    ///
    ///  - returns: RAC Signal
    func loadUserInfo(uid:String) ->RACSignal{
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid":uid]
        return request(.GET, urlString: urlString, parameters: params)
    }
}
